﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace com.calitha.goldparser.sql
{
    public class CodeGenerator
    {
        string oldSql="";
        string newSql="";
        string name="";
        string value="";

        public string GenerateCode(string newSqlQuery,string oldSqlQuery, Replacements parameters, CodeTemplateWrapper template)
        {
            oldSql = oldSqlQuery;
            newSql = newSqlQuery;
            string result="";
            //Code Start
            result = ReplaceVariables(template.CodeStart);
            result += ReplaceVariables(template.SqlParameterStart);
            foreach (Replacement replace in parameters)
            {
                name = replace.newId;
                //we have to remove this symbol -> '' from string terminals 
                if (replace.tokenForReplace.Symbol.Id == (int)SymbolConstants.SYMBOL_STRINGLITERAL)
                {
                    value = "\"" + replace.tokenForReplace.Text.Substring(1, replace.tokenForReplace.Text.Length - 2) + "\"";
                }
                else
                {
                    value = replace.tokenForReplace.Text; //text is the value of the parameter;
                }
                result += ReplaceVariables(template.SqlParameter);
            }
            result += ReplaceVariables(template.SqlParameterEnd);
            result += ReplaceVariables(template.CodeEnd);
            return result;
        }
        private string ReplaceVariables(string s)
        {
            s = s.Replace("$oldsql", oldSql);
            s = s.Replace("$newsql", newSql);
            s = s.Replace("$name", name);
            return s.Replace("$value", value);
        }
    }
}
